<template>
  <div class="member-manage">
    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon level-icon">
                <i class="el-icon-medal"></i>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statistics.totalLevels || 0 }}</div>
                <div class="stats-label">会员等级</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon points-icon">
                <i class="el-icon-coin"></i>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statistics.totalPointsEarned || 0 }}</div>
                <div class="stats-label">总积分发放</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon users-icon">
                <i class="el-icon-user"></i>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statistics.activeUsers || 0 }}</div>
                <div class="stats-label">活跃用户</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon records-icon">
                <i class="el-icon-document"></i>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ statistics.totalPointsRecords || 0 }}</div>
                <div class="stats-label">积分记录</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" class="member-tabs">
      <!-- 会员等级管理 -->
      <el-tab-pane label="会员等级" name="levels">
        <div class="tab-header">
          <el-button type="primary" @click="openLevelDialog()">
            <i class="el-icon-plus"></i> 新增等级
          </el-button>
        </div>
        
        <el-table :data="levels" v-loading="levelsLoading" style="width: 100%">
          <el-table-column prop="levelName" label="等级名称" width="120" />
          <el-table-column prop="levelCode" label="等级代码" width="120" />
          <el-table-column prop="minPoints" label="最低积分" width="100" />
          <el-table-column prop="maxPoints" label="最高积分" width="100">
            <template slot-scope="scope">
              {{ scope.row.maxPoints || '无限制' }}
            </template>
          </el-table-column>
          <el-table-column prop="discountRate" label="折扣率" width="100">
            <template slot-scope="scope">
              {{ (scope.row.discountRate * 100).toFixed(0) }}%
            </template>
          </el-table-column>
          <el-table-column prop="pointsRatio" label="积分倍率" width="100">
            <template slot-scope="scope">
              {{ scope.row.pointsRatio }}x
            </template>
          </el-table-column>
          <el-table-column prop="userCount" label="用户数量" width="100" />
          <el-table-column prop="isActive" label="状态" width="80">
            <template slot-scope="scope">
              <el-tag :type="scope.row.isActive ? 'success' : 'danger'">
                {{ scope.row.isActive ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button size="small" @click="openLevelDialog(scope.row)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteLevel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>

      <!-- 积分管理 -->
      <el-tab-pane label="积分管理" name="points">
        <div class="tab-header">
          <div class="search-box">
            <el-input
              v-model="pointsSearch.userName"
              placeholder="用户名"
              style="width: 200px; margin-right: 10px;"
              clearable
            />
            <el-select
              v-model="pointsSearch.changeType"
              placeholder="变化类型"
              style="width: 150px; margin-right: 10px;"
              clearable
            >
              <el-option label="订单奖励" value="EARN_ORDER" />
              <el-option label="评论奖励" value="EARN_REVIEW" />
              <el-option label="积分抵扣" value="SPEND_DISCOUNT" />
              <el-option label="管理员调整" value="ADMIN_ADJUST" />
            </el-select>
            <el-button type="primary" @click="searchPoints">搜索</el-button>
            <el-button @click="resetPointsSearch">重置</el-button>
          </div>
          <el-button type="primary" @click="openAdjustDialog">
            <i class="el-icon-edit"></i> 调整积分
          </el-button>
        </div>

        <el-table :data="pointsRecords" v-loading="pointsLoading" style="width: 100%">
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="userNickname" label="用户" width="120" />
          <el-table-column prop="pointsChange" label="积分变化" width="120">
            <template slot-scope="scope">
              <span :class="scope.row.pointsChange > 0 ? 'positive' : 'negative'">
                {{ scope.row.pointsChange > 0 ? '+' : '' }}{{ scope.row.pointsChange }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="pointsBalance" label="积分余额" width="120" />
          <el-table-column prop="changeType" label="变化类型" width="120">
            <template slot-scope="scope">
              <el-tag :type="getChangeTypeColor(scope.row.changeType)">
                {{ getChangeTypeText(scope.row.changeType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="200" />
          <el-table-column prop="createTime" label="时间" width="180">
            <template slot-scope="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            @size-change="handlePointsSizeChange"
            @current-change="handlePointsCurrentChange"
            :current-page="pointsCurrentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pointsPageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pointsTotal"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 等级编辑对话框 -->
    <el-dialog
      :title="levelDialogTitle"
      :visible.sync="levelDialogVisible"
      width="600px"
      @close="closeLevelDialog"
    >
      <el-form :model="currentLevel" :rules="levelRules" ref="levelForm" label-width="120px">
        <el-form-item label="等级名称" prop="levelName">
          <el-input v-model="currentLevel.levelName" placeholder="请输入等级名称" />
        </el-form-item>
        <el-form-item label="等级代码" prop="levelCode">
          <el-input v-model="currentLevel.levelCode" placeholder="请输入等级代码" />
        </el-form-item>
        <el-form-item label="最低积分" prop="minPoints">
          <el-input-number v-model="currentLevel.minPoints" :min="0" />
        </el-form-item>
        <el-form-item label="最高积分" prop="maxPoints">
          <el-input-number v-model="currentLevel.maxPoints" :min="0" />
        </el-form-item>
        <el-form-item label="折扣率" prop="discountRate">
          <el-input-number v-model="currentLevel.discountRate" :min="0.1" :max="1" :step="0.01" />
        </el-form-item>
        <el-form-item label="积分倍率" prop="pointsRatio">
          <el-input-number v-model="currentLevel.pointsRatio" :min="1" :step="0.1" />
        </el-form-item>
        <el-form-item label="等级颜色" prop="levelColor">
          <el-color-picker v-model="currentLevel.levelColor" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="currentLevel.description" :rows="3" />
        </el-form-item>
        <el-form-item label="状态" prop="isActive">
          <el-switch v-model="currentLevel.isActive" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeLevelDialog">取消</el-button>
        <el-button type="primary" @click="saveLevelDialog" :loading="levelSaving">确定</el-button>
      </div>
    </el-dialog>

    <!-- 积分调整对话框 -->
    <el-dialog
      title="调整用户积分"
      :visible.sync="adjustDialogVisible"
      width="400px"
      @close="closeAdjustDialog"
    >
      <el-form :model="adjustForm" :rules="adjustRules" ref="adjustForm" label-width="100px">
        <el-form-item label="用户ID" prop="userId">
          <el-input-number v-model="adjustForm.userId" :min="1" />
        </el-form-item>
        <el-form-item label="积分变化" prop="points">
          <el-input-number v-model="adjustForm.points" />
        </el-form-item>
        <el-form-item label="调整说明" prop="description">
          <el-input type="textarea" v-model="adjustForm.description" :rows="3" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeAdjustDialog">取消</el-button>
        <el-button type="primary" @click="saveAdjustDialog" :loading="adjustSaving">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'MemberManage',
  data() {
    return {
      activeTab: 'levels',
      statistics: {},
      
      // 等级管理
      levels: [],
      levelsLoading: false,
      levelDialogVisible: false,
      levelDialogTitle: '新增等级',
      levelSaving: false,
      currentLevel: {
        levelName: '',
        levelCode: '',
        minPoints: 0,
        maxPoints: null,
        discountRate: 1.0,
        pointsRatio: 1.0,
        levelColor: '#409EFF',
        description: '',
        isActive: true
      },
      levelRules: {
        levelName: [{ required: true, message: '请输入等级名称', trigger: 'blur' }],
        levelCode: [{ required: true, message: '请输入等级代码', trigger: 'blur' }],
        minPoints: [{ required: true, message: '请输入最低积分', trigger: 'blur' }],
        discountRate: [{ required: true, message: '请输入折扣率', trigger: 'blur' }],
        pointsRatio: [{ required: true, message: '请输入积分倍率', trigger: 'blur' }]
      },
      
      // 积分管理
      pointsRecords: [],
      pointsLoading: false,
      pointsCurrentPage: 1,
      pointsPageSize: 10,
      pointsTotal: 0,
      pointsSearch: {
        userName: '',
        changeType: ''
      },
      
      // 积分调整
      adjustDialogVisible: false,
      adjustSaving: false,
      adjustForm: {
        userId: null,
        points: 0,
        description: ''
      },
      adjustRules: {
        userId: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
        points: [{ required: true, message: '请输入积分变化', trigger: 'blur' }],
        description: [{ required: true, message: '请输入调整说明', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.loadStatistics()
    this.loadLevels()
    this.loadPointsRecords()
  },
  methods: {
    // 加载统计信息
    async loadStatistics() {
      try {
        const response = await this.request.get('/api/member/statistics')
        if (response.code === '200') {
          this.statistics = response.data
        } else {
          this.$message.error(response.msg || '加载统计信息失败')
        }
      } catch (error) {
        console.error('加载统计信息失败:', error)
        this.$message.error('加载统计信息失败')
      }
    },
    
    // 加载等级列表
    async loadLevels() {
      this.levelsLoading = true
      try {
        const response = await this.request.get('/api/member/level/page', {
          params: { pageNum: 1, pageSize: 100 }
        })
        if (response.code === '200') {
          this.levels = response.data.records
        } else {
          this.$message.error(response.msg || '加载等级列表失败')
        }
      } catch (error) {
        console.error('加载等级列表失败:', error)
        this.$message.error('加载等级列表失败')
      } finally {
        this.levelsLoading = false
      }
    },
    
    // 加载积分记录
    async loadPointsRecords() {
      this.pointsLoading = true
      try {
        const params = {
          pageNum: this.pointsCurrentPage,
          pageSize: this.pointsPageSize,
          ...this.pointsSearch
        }
        const response = await this.request.get('/api/member/points/page', { params })
        if (response.code === '200') {
          this.pointsRecords = response.data.records
          this.pointsTotal = response.data.total
        } else {
          this.$message.error(response.msg || '加载积分记录失败')
        }
      } catch (error) {
        console.error('加载积分记录失败:', error)
        this.$message.error('加载积分记录失败')
      } finally {
        this.pointsLoading = false
      }
    },
    
    // 等级对话框
    openLevelDialog(level = null) {
      if (level) {
        this.levelDialogTitle = '编辑等级'
        this.currentLevel = { ...level }
      } else {
        this.levelDialogTitle = '新增等级'
        this.currentLevel = {
          levelName: '',
          levelCode: '',
          minPoints: 0,
          maxPoints: null,
          discountRate: 1.0,
          pointsRatio: 1.0,
          levelColor: '#409EFF',
          description: '',
          isActive: true
        }
      }
      this.levelDialogVisible = true
    },
    
    closeLevelDialog() {
      this.levelDialogVisible = false
      this.$refs.levelForm.resetFields()
    },
    
    async saveLevelDialog() {
      try {
        await this.$refs.levelForm.validate()
        this.levelSaving = true
        
        const response = await this.request.post('/api/member/level', this.currentLevel)
        if (response.code === '200') {
          this.$message.success('保存成功')
          this.closeLevelDialog()
          this.loadLevels()
          this.loadStatistics()
        } else {
          this.$message.error(response.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败')
      } finally {
        this.levelSaving = false
      }
    },
    
    async deleteLevel(levelId) {
      try {
        await this.$confirm('确定要删除这个等级吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await this.request.delete(`/api/member/level/${levelId}`)
        if (response.code === '200') {
          this.$message.success('删除成功')
          this.loadLevels()
          this.loadStatistics()
        } else {
          this.$message.error(response.msg || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },
    
    // 积分调整对话框
    openAdjustDialog() {
      this.adjustForm = {
        userId: null,
        points: 0,
        description: ''
      }
      this.adjustDialogVisible = true
    },
    
    closeAdjustDialog() {
      this.adjustDialogVisible = false
      this.$refs.adjustForm.resetFields()
    },
    
    async saveAdjustDialog() {
      try {
        await this.$refs.adjustForm.validate()
        this.adjustSaving = true
        
        const response = await this.request.post('/api/member/points/adjust', this.adjustForm)
        if (response.code === '200') {
          this.$message.success('积分调整成功')
          this.closeAdjustDialog()
          this.loadPointsRecords()
          this.loadStatistics()
        } else {
          this.$message.error(response.msg || '积分调整失败')
        }
      } catch (error) {
        console.error('积分调整失败:', error)
        this.$message.error('积分调整失败')
      } finally {
        this.adjustSaving = false
      }
    },
    
    // 积分搜索
    searchPoints() {
      this.pointsCurrentPage = 1
      this.loadPointsRecords()
    },
    
    resetPointsSearch() {
      this.pointsSearch = {
        userName: '',
        changeType: ''
      }
      this.pointsCurrentPage = 1
      this.loadPointsRecords()
    },
    
    // 分页处理
    handlePointsSizeChange(val) {
      this.pointsPageSize = val
      this.loadPointsRecords()
    },
    
    handlePointsCurrentChange(val) {
      this.pointsCurrentPage = val
      this.loadPointsRecords()
    },
    
    // 工具方法
    getChangeTypeColor(type) {
      const colors = {
        'EARN_ORDER': 'success',
        'EARN_REVIEW': 'success',
        'SPEND_DISCOUNT': 'warning',
        'ADMIN_ADD': 'primary',
        'ADMIN_DEDUCT': 'danger'
      }
      return colors[type] || 'info'
    },
    
    getChangeTypeText(type) {
      const texts = {
        'EARN_ORDER': '订单奖励',
        'EARN_REVIEW': '评论奖励',
        'SPEND_DISCOUNT': '积分抵扣',
        'ADMIN_ADD': '管理员增加',
        'ADMIN_DEDUCT': '管理员扣除'
      }
      return texts[type] || type
    },
    
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.member-manage {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  height: 100px;
}

.stats-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.level-icon {
  background: linear-gradient(45deg, #667eea 0%, #764ba2 100%);
}

.points-icon {
  background: linear-gradient(45deg, #f093fb 0%, #f5576c 100%);
}

.users-icon {
  background: linear-gradient(45deg, #4facfe 0%, #00f2fe 100%);
}

.records-icon {
  background: linear-gradient(45deg, #43e97b 0%, #38f9d7 100%);
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: #666;
  margin-top: 5px;
}

.member-tabs {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.tab-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: center;
}

.positive {
  color: #67c23a;
  font-weight: bold;
}

.negative {
  color: #f56c6c;
  font-weight: bold;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .member-manage {
    padding: 10px;
  }
  
  .tab-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .search-box {
    flex-wrap: wrap;
    gap: 10px;
  }
}
</style> 